<template>
  <view class="container">

    <scroll-view
      scroll-y
      scroll-with-animation
      enable-passive
      bounces
      enhanced
      :show-scrollbar="false"
      class="scroll-view"
      @scroll="($event) => onScroll($event.detail?.scrollTop)"
    >
      <view class="py-12">
        <BasicsForm @register="register" />
        <Empty v-if="isEmpty" text="暂无表单项" />
      </view>
    </scroll-view>
    <ScrollTop ref="scrollTopRef" :bottom="340" :is-page-model="false" @scroll-to="onScrollTo" />
    <view class="add-topic disFlxCC" @click.stop="handleAddFormItem()">
      <text class="ali-icon icon-tianjia mb-4"></text>
      <text>题目</text>
    </view>
  </view>
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormSchema, type ComponentProps } from '@/components/Form';
  import { onMounted, ref, getCurrentInstance, inject, type Ref } from 'vue';
  import Empty from '@/components/Empty/Empty.vue';
  import { navigateTo } from '@/router';
  import ScrollTop, { type ScrollTopExpose } from '@/components/ScrollTop/index.vue';
  import { isArray, isNumber, isString } from 'lodash-es';
  import { propTypes } from '@/utils/propTypes';
  import { IsRequired } from '@/enums/formEnum';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import type { ComponentType } from '@/components/Form/types';
  import type { Localdata } from '@/components/Form/types';
  import { Toast } from '@/utils';
  import { getBoFormItemGetById } from '@/api/businessOpportunities';
  import type { BoFormAddOrUpdateItmeData } from '@/api/businessOpportunities/type';
  import type { ReleaseTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import CustomTopTips from '@/components/CustomTopTips/index.vue';

  const releaseType = inject<Ref<ReleaseTypeEnum>>('releaseType');

  const props = defineProps({
    id: propTypes.number,
  });

  const _this = getCurrentInstance()?.proxy;

  const [register, { getSchemas, appendSchemaByField }] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    disabled: true,
    formInteractionMode: 'edit',
    onToolbarEditEvent: async (schema) => await toUpdate(schema),
    onToolbarCopyEvent: (schema) => handleAddFormItem(schema),
  });

  const scrollViewRef = ref<{ scrollTo: (op: { top: number; animated?: boolean }) => void } | null>(
    null,
  );
  const scrollTopRef = ref<ScrollTopExpose | null>(null);

  const isEmpty = ref(true);

  const handleAddFormItem = async (item?: FormSchema) => {
    if (item) item.field = '';
    const data = await toUpdate(item);
    appendSchemaByField({
      ...data,
    });
    isEmpty.value = false;
  };

  function toUpdate(item?: FormSchema): Promise<FormSchema> {
    return new Promise((resolve) => {
      navigateTo({
        name: 'createFormItem',
        options: {
          item,
          success: (data) => resolve(data),
        },
      });
    });
  }

  onMounted(async () => {
    const res = await getBoFormItemGetById(props.id, releaseType?.value);
    res.formItemList.forEach((item) => {
      appendSchemaByField({
        field: item.id.toString(),
        label: item.showName,
        component: item.itemType,
        defaultValue: item.itemDefault,
        required: item.isRequired === IsRequired.REQUIRED,
        dataType: item.dataType,
        dynamicDisabled: item.disabled,
        componentProps: {
          placeholder: item.value,
          localdata: localDataMapping(item.customFormItemAnswerList, {
            label: 'words',
            value: 'id',
          }),
        },
      });
    });
    if (res.formItemList.length) {
      isEmpty.value = false;
    }
    uni
      .createSelectorQuery()
      .in(_this)
      .select('.scroll-view')
      .node((res) => {
        scrollViewRef.value = res.node;
      })
      .exec();
  });

  function onScroll(scrollTop?: number) {
    isNumber(scrollTop) && scrollTopRef.value?.onScroll({ scrollTop: scrollTop });
  }

  function onScrollTo() {
    scrollViewRef.value?.scrollTo?.({ top: 1, animated: true });
  }

  defineExpose({
    submit: () => {
      return new Promise(async (resolve, reject) => {
        try {
          let res = await getSchemas();
          if (!res.length) return Toast('请添加题目');
          const data: BoFormAddOrUpdateItmeData = {
            customFromId: props.id,
            customFormItemList: [],
          };
          res.forEach((v) => {
            const id = Number.isNaN(v.field) ? null : Number(v.field);
            const label = v.label as string;
            const componentProps = v.componentProps as ComponentProps;
            const localdata =
              componentProps && isArray(componentProps?.localdata)
                ? (componentProps?.localdata as Localdata[])
                : [];
            data.customFormItemList.push({
              id: id,
              name: label,
              showName: label,
              itemType: v.component as ComponentType,
              isRequired: v.required ? IsRequired.REQUIRED : IsRequired.NOTREQUIRED,
              value: componentProps?.placeholder as string,
              customFormItemAnswerDtoList: localdata.map((v) => {
                return {
                  id: isString(v.value) ? null : v.value,
                  words: v.text,
                };
              }),
            });
          });
          resolve(data);
        } catch (error) {
          reject();
        }
      });
    },
  });
</script>

<style lang="scss" scoped>
  .container {
    position: relative;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100%;
    overflow: hidden;
    .scroll-view {
      width: 100vw;
      height: 100%;
    }
    .add-topic {
      position: fixed;
      right: 32rpx;
      bottom: 340rpx;
      width: 104rpx;
      height: 104rpx;
      border-radius: 50%;
      background: linear-gradient(0deg, #2878ff 0%, #7bacff 100%);
      box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16);
      color: #fff;
      font-size: 24rpx;
      z-index: 997;
    }
  }
</style>
